package com.jarchie.seemovies.helper;

import android.content.Context;

import com.jarchie.seemovies.gen.GreenDaoManager;
import com.jarchie.seemovies.gen.UserBeanDao;
import com.jarchie.seemovies.bean.UserBean;
import com.jarchie.seemovies.utils.TipUtils;

import java.util.List;

/**
 * Created by Jarchie on 2017\11\16.
 * 描述：数据库操作的工具类
 */

@SuppressWarnings("unused")
public class UserDBHelper {

    //插入数据
    public static void insertUser(Long id, String userName, String passWord) {
        UserBeanDao userBeanDao = GreenDaoManager.getInstance().getDaoSession().getUserBeanDao();
        UserBean userBean = new UserBean(id, userName, passWord);
        userBeanDao.insert(userBean);
    }

    //删除数据
    public static void deleteUser(String userName) {
        UserBeanDao userBeanDao = GreenDaoManager.getInstance().getDaoSession().getUserBeanDao();
        UserBean findUser = userBeanDao.queryBuilder().where(UserBeanDao.Properties.UserName.eq(userName)).build().unique();
        if (findUser != null) {
            userBeanDao.deleteByKey(findUser.getId());
        }
    }

    //修改数据
    public static void updateUser(Context mContext, String prevName, String newName, String newPwd) {
        UserBeanDao userBeanDao = GreenDaoManager.getInstance().getDaoSession().getUserBeanDao();
        UserBean findUsr = userBeanDao.queryBuilder().where(UserBeanDao.Properties.UserName.eq(prevName)).build().unique();
        if (findUsr != null) {
            findUsr.setUserName(newName);
            findUsr.setPassWord(newPwd);
            GreenDaoManager.getInstance().getDaoSession().getUserBeanDao().update(findUsr);
            TipUtils.showToast(mContext, "修改成功");
        } else {
            TipUtils.showToast(mContext, "用户不存在");
        }
    }

    //查询数据
    public static List<UserBean> queryAllData() {
        UserBeanDao userBeanDao = GreenDaoManager.getInstance().getDaoSession().getUserBeanDao();
        return userBeanDao.queryBuilder().list();
    }

    //按用户名查找
    public static UserBean queryBean(String userName){
        UserBeanDao userBeanDao = GreenDaoManager.getInstance().getDaoSession().getUserBeanDao();
        return userBeanDao.queryBuilder().where(UserBeanDao.Properties.UserName.eq(userName)).build().unique();
    }

    //按Id降序查询最后一个
    public static UserBean queryLastBean(){
        UserBeanDao userBeanDao = GreenDaoManager.getInstance().getDaoSession().getUserBeanDao();
        return userBeanDao.queryBuilder().where(UserBeanDao.Properties.Id.notEq(9999)).orderDesc(UserBeanDao.Properties.Id).limit(1).build().unique();
    }

}
